本篇學習筆記來不及趕完,只好先上傳之後再改了......
import { Controller, Get, HttpException, HttpStatus } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
throw new HttpException('發生錯誤!',HttpStatus.BAD_REQUEST)
return this.appService.getHello();
}
}
Api測試結果:
自定義回傳格式:
import { Controller, Get, HttpException, HttpStatus } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
const obj={
code:HttpStatus.BAD_REQUEST,
message:'發生錯誤!'
}
throw new HttpException(obj,HttpStatus.BAD_REQUEST)
return this.appService.getHello();
}
}
api測試結果:
內建回傳格式:
import { BadRequestException, Controller, Get, HttpException, HttpStatus } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
throw new BadRequestException('發生錯誤!');
return this.appService.getHello();
}
}
api測試結果:
import { ArgumentsHost, Catch, ExceptionFilter, HttpException } from '@nestjs/common';
@Catch(HttpException)
export class HttpFilter<T extends HttpException> implements ExceptionFilter<T> {
catch(exception: T, host: ArgumentsHost) {}
}
解釋說明:
ArguementsHost是一個helper class,我們可以透過它來獲得一些跟該請求相關的參數,比如request、response物件等等的,再來也可以為不同的底層參數做封裝.
關於host可使用的方法,官網有特別寫在這邊https://docs.nestjs.com/fundamentals/execution-context#execution-context